package com.design.myiterator.demo1;

import java.util.ArrayList;
import java.util.List;

// 迭代器接口
interface Iterator<T> {
    boolean hasNext();
    T next();
}

// 可迭代对象接口
interface Iterable<T> {
    Iterator<T> iterator();
}

// 自定义集合类
class MyCollection<T> implements Iterable<T> {
    private List<T> items = new ArrayList<>();

    public void addItem(T item) {
        items.add(item);
    }

    @Override
    public Iterator<T> iterator() {
        return new MyIterator<>(items);
    }
}

// 自定义迭代器类
class MyIterator<T> implements Iterator<T> {
    private List<T> items;
    private int position = 0;

    public MyIterator(List<T> items) {
        this.items = items;
    }

    @Override
    public boolean hasNext() {
        return position < items.size();
    }

    @Override
    public T next() {
        T item = items.get(position);
        position++;
        return item;
    }
}

public class IteratorPatternDemo {
    public static void main(String[] args) {
        MyCollection<String> collection = new MyCollection<>();
        collection.addItem("Item 1");
        collection.addItem("Item 2");
        collection.addItem("Item 3");

        Iterator<String> iterator = collection.iterator();
        while (iterator.hasNext()) {
            String item = iterator.next();
            System.out.println("Item: " + item);
        }
    }
}
